package itext.test.example;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 *
 * @author Bruno Lowagie (iText Software)
 */
public class HighLightByAddingContent {

	public static final String SRC = "d:/1.pdf";
	public static final String DEST = "d:/test1.pdf";

	public static void main(String[] args) throws IOException, DocumentException {
		File file = new File(DEST);
		file.getParentFile().mkdirs();
		new HighLightByAddingContent().manipulatePdf2(SRC, DEST);
	}

	// 覆盖层添加文字
	public void manipulatePdf2(String src, String dest) throws IOException, DocumentException {
		float x = 37f;
		float y = 775.5f;
		float width = 134.84f ;
		float height =  14.7f;
		PdfReader reader = new PdfReader(src);
		PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
		PdfContentByte canvas = stamper.getOverContent(1);
		canvas.saveState();
		canvas.setColorFill(BaseColor.WHITE);
		canvas.rectangle(x, y,width ,height);
		canvas.fill();
		canvas.restoreState();
		// 开始写入文本
		canvas.beginText();

		// BaseFont bf =
		// BaseFont.createFont(URLDecoder.decode(CutAndPaste.class.getResource("/AdobeSongStd-Light.otf").getFile()),
		// BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
		BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
		Font font = new Font(bf, 10, Font.BOLD);
		// 设置字体和大小
		canvas.setFontAndSize(font.getBaseFont(), 12);
		// 设置字体的输出位置
		canvas.setTextMatrix(x, y);
		// 要输出的text
		canvas.showText("山东省");

		canvas.endText();

		stamper.close();
		reader.close();
	}

	public void manipulatePdf1(String src, String dest) throws IOException, DocumentException {
		PdfReader reader = new PdfReader(src);
		PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
		PdfContentByte canvas = stamper.getOverContent(1);
		canvas.saveState();
		canvas.setColorFill(BaseColor.YELLOW);
		canvas.rectangle(35.96, 773.14, 134.84, 16.29);
		canvas.fill();
		canvas.restoreState();
		stamper.close();
		reader.close();
	}

}
